package com.ravi.controller;

import com.ravi.common.R;
import com.ravi.core.patient.BasePatient;
import com.ravi.core.queue.CheckUpQueue;
import com.ravi.core.queue.HashQueueManager;
import com.ravi.entity.CheckRoom;
import com.ravi.entity.PatientQueueInfo;
import com.ravi.exception.ErrorCode;
import com.ravi.service.CheckAreaService;
import com.ravi.service.QueueService;
import com.ravi.util.jwt.JWTUtils;
import com.ravi.vo.AreaRoomVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.BlockingQueue;

@RestController
@CrossOrigin
@RequestMapping("/waitQueue")
@Slf4j
public class WaitingQueueController {

	@Autowired
	private QueueService queueService;

	@Autowired
	private CheckAreaService checkAreaService;

	@PostMapping("/sign/{id}")
	public R signForCheckUp(@PathVariable String id) {
		Integer patientId = Integer.parseInt(id);
		// TODO: 全局处理运行时异常
		boolean needFirstSign = queueService.needFirstSign(patientId);
		if (needFirstSign) {
			queueService.firstSign(patientId);
			// 导检算法安排并发送消息
		} else {
			// 校验排队信息是否合法
			PatientQueueInfo patientInfo = queueService.enqueueValid(patientId);
			// 签到入队
			queueService.enqueue(patientInfo);
		}
		return R.ok();
	}

	@GetMapping("/queue/{id}")
	public R getQueue(@PathVariable("id") String id, Integer index, Integer size) {
		Integer queueId = Integer.parseInt(id);
		boolean empty = queueService.queueInfoEmpty(queueId);
		if (empty) {
			return R.error(ErrorCode.QUEUE_NOT_FOUND, "找不到队列!");
		}
		// 若队列id合法
		CheckUpQueue checkUpQueue = HashQueueManager.getQueue(queueId);
		BlockingQueue<BasePatient> mCheckQueue = checkUpQueue.getMCheckQueue();
		Object[] objects = mCheckQueue.toArray();
		Arrays.sort(objects);
		List<Object> ret = new ArrayList();
		for (int i = index, temp = 0; i < objects.length; i++) {
			if (temp >= size) {
				break;
			}
			ret.add(objects[i]);
			temp++;
		}
		return R.ok().put("queue", ret).put("total", objects.length);
	}

	/**
	 * 大厅展示Api
	 * @param request
	 * @return
	 */
	@GetMapping("/queues")
	public R getQueuesInArea(HttpServletRequest request) {
		final Integer areaId = JWTUtils.getAreaId(request.getHeader("token"));
		try{
			AreaRoomVo areaRoomVo = checkAreaService.getAreaInfoById(areaId);
			List<CheckRoom> rooms = areaRoomVo.getRooms();
			List<CheckUpQueue> queueList = new ArrayList<>();
			for (CheckRoom room : rooms) {
				queueList.add(HashQueueManager.getQueue(room.getRoomId()));
			}
			return R.ok().put("queueList", queueList);
		}catch (Exception e) {
			return R.error(e.getMessage());
		}
	}
}
